package cn.rokhdelar.ams.management.service.impl;

import cn.rokhdelar.ams.common.domain.vo.PageVO;
import cn.rokhdelar.ams.management.domain.po.SysAnnouncement;
import cn.rokhdelar.ams.management.domain.po.SysUser;
import cn.rokhdelar.ams.management.domain.query.AnnouncementQuery;
import cn.rokhdelar.ams.management.domain.vo.AnnouncementVO;
import cn.rokhdelar.ams.management.mapper.SysAnnouncementMapper;
import cn.rokhdelar.ams.management.service.SysAnnouncementService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class SysAnnouncementServiceImpl extends ServiceImpl<SysAnnouncementMapper, SysAnnouncement>
        implements SysAnnouncementService {

    private final SysAnnouncementMapper sysAnnouncementMapper;
    @Override
    public PageVO<AnnouncementVO> getAnnouncementsByPage(AnnouncementQuery query) {
        Page<AnnouncementVO> page = query.toPageDefaultSortByCreateTime();
        MPJLambdaWrapper<SysAnnouncement> wrapper = new MPJLambdaWrapper<SysAnnouncement>()
                .selectAll(SysAnnouncement.class)
                .leftJoin(SysUser.class, SysUser::getId, SysAnnouncement::getAuthorId, ext ->
                        ext.selectAs(SysUser::getName, AnnouncementVO::getAuthorName))
                .eq(query.getTitle() != null, SysAnnouncement::getTitle, query.getTitle())
                .eq(query.getPublished() != null, SysAnnouncement::getPublished, query.getPublished())
                .between(query.getStartDateTime() != null && query.getEndDateTime() != null,
                        SysAnnouncement::getStartDateTime, query.getStartDateTime(), query.getEndDateTime());
        Page<AnnouncementVO> announcementVOPage = sysAnnouncementMapper.selectJoinPage(page, AnnouncementVO.class, wrapper);
        return PageVO.of(announcementVOPage, AnnouncementVO.class);
    }

    @Override
    public AnnouncementVO getAnnouncement(String id) {
        MPJLambdaWrapper<SysAnnouncement> wrapper = new MPJLambdaWrapper<SysAnnouncement>()
                .selectAll(SysAnnouncement.class)
                .leftJoin(SysUser.class, SysUser::getId, SysAnnouncement::getAuthorId, ext ->
                        ext.selectAs(SysUser::getName, AnnouncementVO::getAuthorName))
                .eq(SysAnnouncement::getId, id);
        return sysAnnouncementMapper.selectJoinOne(AnnouncementVO.class, wrapper);
    }
}
